package com.hao.tool.web.component;

import com.hao.tool.common.util.HttpUtil;
import com.hao.tool.common.util.JsonKitUtil;
import com.hao.tool.common.util.NetworkUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * api切面日志
 *
 * @author Sawyer
 */
@Aspect
@Component
@Slf4j
public class ApiLogAop {


    @Pointcut(value = "@annotation(com.hao.tool.common.annotion.ApiLogPoint)")
    private void apiLogPoint() {

    }

    @Before(value = "apiLogPoint()")
    public void before(JoinPoint joinPoint) {
    }


    @AfterReturning(value = "apiLogPoint()", returning = "returnObject")
    public void afterReturning(JoinPoint joinPoint, Object returnObject) {
        final HttpServletRequest request = HttpUtil.getRequest();
        log.info("接收到到来自客户端[{}]的请求,编号为:{},内容如下: ", NetworkUtil.getIpAddress(request), "0");
        log.info("请求路径: {}", request.getRequestURI());
        log.info("请求参数: {}", JsonKitUtil.getString(request.getParameterMap()));
        log.info("授权码: {}", request.getHeader("token"));
        log.info("请求体: {}", getRequestBody(request));
        log.info("服务器端返回值: {}", JsonKitUtil.getString(returnObject));
        log.info("");
    }

    @AfterThrowing(value = "apiLogPoint()", throwing = "e")
    public void afterThrowing(JoinPoint joinPoint, Throwable e) {
        final HttpServletRequest request = HttpUtil.getRequest();
        log.info("接收到到来自客户端[{}]的请求,编号为:{},内容如下: ", NetworkUtil.getIpAddress(request), "0");
        log.info("请求路径: {}", request.getRequestURI());
        log.info("请求参数: {}", JsonKitUtil.getString(request.getParameterMap()));
        log.info("授权码: {}", request.getHeader("token"));
        log.info("请求体: {}", getRequestBody(request));
        log.info("服务器端返回值: {}", ExceptionUtils.getMessage(e));
        log.info("");
    }

    /**
     * 获取请求体
     */
    private String getRequestBody(final HttpServletRequest request) {
        StringBuilder requestBodyBuilder = new StringBuilder();
        try (InputStream inputStream = request.getInputStream();
             BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));) {
            char[] charBuffer = new char[128];
            int bytesRead;
            while ((bytesRead = bufferedReader.read(charBuffer)) != -1) {
                requestBodyBuilder.append(charBuffer, 0, bytesRead);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return requestBodyBuilder.toString();
    }
}
